from mcp.server.fastmcp import FastMCP
import operator

# Create an MCP server
mcp = FastMCP("Calculator Server")

@mcp.tool()
def calculate(a: float, op: str, b: float) -> str:
    """Performs a basic arithmetic operation."""
    import math
    ops = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        'sqrt': lambda x, _: x**0.5,
        'square': lambda x, _: x**2,
        'cbrt': lambda x, _: x**(1/3),
        'log': lambda x, _: math.log(x) if x > 0 else 'Error: Logarithm domain error',
    }
    if op not in ops:
        return f"Error: Invalid operator '{op}'"
    if op == '/' and b == 0:
        return "Error: Division by zero"
    if op == 'sqrt':
        if a < 0:
            return "Error: Cannot take square root of negative number"
        result = ops[op](a, None)
        return f"Result: √{a} = {result}"
    if op == 'log':
        if a <= 0:
            return "Error: Logarithm domain error"
        result = ops[op](a, None)
        return f"Result: log({a}) = {result}"
    if op == 'square':
        result = ops[op](a, None)
        return f"Result: {a}^2 = {result}"
    if op == 'cbrt':
        result = ops[op](a, None)
        return f"Result: ∛{a} = {result}"
    result = ops[op](a, b)
    return f"Result: {a} {op} {b} = {result}"

if __name__ == "__main__":
    mcp.run(transport="stdio")